package org.java.net.socket;

import java.net.*;
import java.util.Vector;
import java.io.*;

public class Server5 {
	
	private ServerSocket server;
	private BManager bMan = new BManager();
	
	public Server5() {}
	
	void startServer()
	{
		try {
			server = new ServerSocket(7777);
			System.out.println("服务器套接字创建完毕");
			while(true)
			{
				Socket socket = server.accept();
				new Chat_Thread(socket).start();
				
				bMan.add(socket);
				
				bMan.sendClientInfo();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println(e);
		}
	}
	
	public static void main(String[] args)
	{
		Server5 server = new Server5();
		server.startServer();
	}
	
	class Chat_Thread extends Thread
	{
		Socket socket;
		private BufferedReader reader;
		private PrintWriter writer;
		
		Chat_Thread(Socket socket)
		{
			this.socket = socket;
		}
		
		public void run()
		{
			try
			{
				reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				writer = new PrintWriter(socket.getOutputStream(), true);
				String msg;
				while((msg=reader.readLine())!=null){
			          System.out.println(msg);
			          bMan.sendToAll(msg);
			    }
			}
			catch(Exception e)
			{}
			finally
			{
				try{
			          bMan.remove(socket);
			          if(reader!=null) reader.close();
			          if(writer!=null) writer.close();
			          if(socket!=null) socket.close();
			          reader=null; writer=null; socket=null;
			          System.out.println("客户机离开.");
			          bMan.sendClientInfo();
			        }catch(Exception e){}
			}
		}
	}
	
	class BManager extends Vector{
	    BManager(){}
	    void add(Socket sock){
	      super.add(sock);
	    }
	    void remove(Socket sock){
	      super.remove(sock);
	    }
	    
	    synchronized void sendToAll(String msg)
	    {
	    	PrintWriter writer = null;
	    	Socket sock;
	    	
	    	for(int i=0; i<size(); i++)
	    	{
	    		sock = (Socket)elementAt(i);
	    		
	    		try
	    		{
	    			writer = new PrintWriter(sock.getOutputStream(), true);
	    		}
	    		catch(IOException ie){}
	    		if(writer != null) writer.println(msg);
	    	}
	    	
	    }
	    
	    synchronized void sendClientInfo()
	    {
	    	String info = "当前聊天人数"+ size();
	    	System.out.println(info);
	    	sendToAll(info);
	    }
	}

}
